package com.weishi.project.sport.movement.thread;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.sport.movement.selection.MovementSelection;
import com.weishi.project.sport.movement.vo.TrainingReportBean;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 增删改
 */
@Component
public class MovementRunnable implements Runnable {

    /**
     * redis 数据库
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 心率表 接口
     */
    @Autowired
    private IHeartRateService heartRateService;

    /**
     * 训练成绩 接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 运动员接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 测功仪数据接口
     */
    @Autowired
    private IDynamometerService dynamometerService;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    /**
     * 训练成绩表 接口
     */
    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 训练课接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    @Autowired
    private ITrainingGroupService trainingGroupService;

    /**
     * 分段成绩 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;




    @Override
    public void run() {
        /**
         * 线程池高并发，使用同步线程做处理
         */
        //同步代码块锁
        synchronized (MovementRunnable.class) {

            /**
             * 运动员端--运动模块--新增心率
             */
            if(MovementSelection.getValue().equals("addHeartRate")){
                /*try {
                    JSONObject jsonObject = (JSONObject) redisTemplate.boundListOps("addHeartRate_heartRate").rightPop();
                    com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("content");
                    List<HeartRate> heartRates = JSON.parseArray(jsonArray.toJSONString(), HeartRate.class);
                    for (int i = 0; i<heartRates.size(); i++){
                        heartRates.get(i).setSportsmanId(Integer.parseInt(redisTemplate.boundListOps("addHeartRate_userId").rightPop().toString()));
                        heartRates.get(i).setCtime(new Date());
                        heartRateService.save(heartRates.get(i));
                    }
                    redisTemplate.boundListOps("addHeartRate_userId").rightPop();
                    redisTemplate.boundListOps("addHeartRate_heartRate").rightPop();

                }catch (Exception e){
                    System.err.println("运动员端--运动模块--新增心率！" + e.getMessage());
                }*/




                /**
                 * 运动员端--新增测功仪数据
                 */
            }else if(MovementSelection.getValue().equals("MovementServiceImpl_addDynamometer")){
                try {
                    TrainingReportBean trainingDetails = (TrainingReportBean)redisTemplate.boundListOps("MovementServiceImpl_addDynamometer_trainingReportBean").rightPop();

                    // 执行新增测功仪操作
                    Dynamometer dynamometer = new Dynamometer();
                    StringUtils.copyProperties(trainingDetails , dynamometer);
                    dynamometer.setCtime(new Date());
                    dynamometer.setSportsmanId(trainingDetails.getUserId());
                    dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getSex());
                    dynamometer.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getName());
                    dynamometerService.save(dynamometer);

                    // 新增测功仪成绩数据
                    DynamometerRanking dynamometerRanking2 = dynamometerRankingService
                            .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                                    .eq(DynamometerRanking::getSportsmanId , trainingDetails.getUserId())
                                    .eq(DynamometerRanking::getGroupId , trainingDetails.getGroupId()));
                    if(StringUtils.isNotNull(dynamometerRanking2)){
                        DynamometerRanking dynamometerRanking = new DynamometerRanking();
                        StringUtils.copyProperties(trainingDetails , dynamometerRanking);
                        dynamometerRanking.setCtime(new Date());
                        dynamometerRanking.setSportsmanId(Long.parseLong(trainingDetails.getUserId().toString()));
                        dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getSex().toString()));
                        dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getName());
                        dynamometerRanking.setId(dynamometerRanking2.getId());
                        dynamometerRanking.setGroupId(Long.parseLong(trainingDetails.getGroupId().toString()));
                        dynamometerRankingService.updateById(dynamometerRanking);
                    }else{
                        DynamometerRanking dynamometerRanking = new DynamometerRanking();
                        StringUtils.copyProperties(trainingDetails , dynamometerRanking);
                        dynamometerRanking.setCtime(new Date());
                        dynamometerRanking.setSportsmanId(Long.parseLong(trainingDetails.getUserId().toString()));
                        dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getSex().toString()));
                        dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getName());
                        dynamometerRanking.setGroupId(Long.parseLong(trainingDetails.getGroupId().toString()));
                        dynamometerRankingService.save(dynamometerRanking);
                    }


                    if(trainingDetails.getIsEnd() == 0){
                        List<DynamometerSubsection> dynamometerSubsection2 = dynamometerSubsectionService
                                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                        .eq(DynamometerSubsection::getSportsmanId , trainingDetails.getUserId())
                                        .eq(DynamometerSubsection::getTrainingDayId , trainingDetails.getTrainingDayId())
                                        .eq(DynamometerSubsection::getGroupId , trainingDetails.getGroupId()));

                        // 更新教练员端的成绩 直接新增
                        TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
                        trainingGroupChannel.setPropellerFrequency(dynamometer.getPropellerFrequency());
                        trainingGroupChannel.setWatt(dynamometer.getWatt());
                        trainingGroupChannel.setPower(dynamometer.getPower());
                        trainingGroupChannel.setRowingKilometers(dynamometer.getMileage().intValue());
                        trainingGroupChannel.setStages(dynamometer.getSegmentNumber()+1);
                        if(dynamometer.getTrainingMode() == 0){
                            trainingGroupChannel.setAchievement(dynamometer.getLengthTime());
                            // 分段成绩
                            String segmentedTiming = "";
                            for (int i = 0; i<dynamometerSubsection2.size(); i++){
                                segmentedTiming += dynamometer.getLengthTime() + " ";
                            }
                            trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                        }else{
                            trainingGroupChannel.setAchievement(dynamometer.getMileage().toString());
                            // 分段成绩
                            String segmentedTiming = "";
                            for (int i = 0; i<dynamometerSubsection2.size(); i++){
                                segmentedTiming += dynamometer.getMileage().toString() + " ";
                            }
                            trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                        }
                        trainingGroupChannel.setGroupId(trainingDetails.getGroupId());
                        trainingGroupChannelService.save(trainingGroupChannel);

                        //同步陆上滑行公里数
                        TrainingGroup trainingGroup = new TrainingGroup();
                        trainingGroup.setId(trainingDetails.getGroupId().intValue());
                        trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
                        trainingGroupService.updateById(trainingGroup);
                        trainingDayService.aggregateData(trainingDetails.getTrainingDayId());

                        /**
                         * 新增数据到 成绩表
                         */
                        TrainingAchievement trainingAchievement = new TrainingAchievement();
                        trainingAchievement.setChannelId(trainingGroupChannel.getId());
                        trainingAchievement.setGroupId(trainingDetails.getGroupId());
                        trainingAchievement.setTrainingDayId(trainingDetails.getTrainingDayId());
                        trainingAchievement.setSportsmanId(trainingDetails.getUserId());
                        trainingAchievement.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , trainingDetails.getUserId())).getName());
                        trainingAchievement.setWeekId(trainingDayService.getById(trainingDetails.getTrainingDayId()).getWeekId());
                        trainingAchievementService.save(trainingAchievement);

                        /**
                         * 查出新增成功后的 channelId 更新到分段成绩表里面
                         */
                        List<DynamometerSubsection> dynamometerSubsection = dynamometerSubsectionService
                                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                        .eq(DynamometerSubsection::getSportsmanId , trainingDetails.getUserId())
                                        .eq(DynamometerSubsection::getTrainingDayId , trainingDetails.getTrainingDayId())
                                        .eq(DynamometerSubsection::getGroupId , trainingDetails.getGroupId()));

                        if(dynamometerSubsection.size() > 0){
                            dynamometerSubsection.forEach( p->{
                                DynamometerSubsection dynamometerSubsections = new DynamometerSubsection();
                                dynamometerSubsections.setChannelId(trainingGroupChannel.getId());
                                dynamometerSubsections.setId(p.getId());
                                dynamometerSubsectionService.updateById(dynamometerSubsections);
                            });
                        }
                    }



                }catch (Exception e){
                    e.printStackTrace();
                }



                /**
                 * 运动员端--新增测功仪数据 结束
                 */








            }else{

            }








        }
    }





}
